<template>
  <el-card>
    <div class="mb-4" style="align-items: center">
      <h3>任务指派</h3>
    </div>
    <el-alert
      title="指派检测任务应遵循就近原则，异地指派需联系网格员确认；完成指派后如需撤销应联系网格员告知情况；指派后五个工作日内未完成检测任务则自动取消指派。"
      type="warning"
      :closable="false"
      show-icon
    />
    <el-row :gutter="20" class="mt-4">
      <el-col :span="16"
        ><div class="grid-content ep-bg-purple" />
        <baidu-map
          class="bm-view"
          :zoom="zoom"
          :center="center"
          :scroll-wheel-zoom="true"
          @ready="handleMapReady"
          @moving="syncCenterAndZoom"
          @moveend="syncCenterAndZoom"
          @zoomend="syncCenterAndZoom"
        >
          <bm-marker
            :position="target"
            :icon="{
              url: '/src/assets/mapIcon/target.gif',
              size: { width: 60, height: 60 }
            }"
            z-index="9999"
            :clicking="false"
          />
          <bm-marker
            v-for="item in showMarkers"
            :key="item.insId"
            :position="item.position"
            :icon="item.icon"
            :clicking="true"
            @click="handleMarkerClick(item)"
            @mouseover="handleMarkerMouseover(item)"
            @mouseout="handleMarkerMouseout(item)"
          />
        </baidu-map>
      </el-col>
      <el-col :span="8">
        <el-divider content-position="left" border-style="dashed"
          ><h4 style="color: dimgrey">反馈信息</h4></el-divider
        >
        <el-descriptions :column="1" size="small" border>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <user />
                </el-icon>
                ID
              </div>
            </template>
            {{ useFeedbackInfoStoreHook().aqiFeedback.fbId
            }}<el-icon
              class="copy-btn"
              style="color: dodgerblue; margin-left: 8px"
              onmouseout="this.style.color='dodgerblue'"
              onmouseover="this.style.color='gray'"
              @click="
                copyPhone(
                  useFeedbackInfoStoreHook().aqiFeedback.fbId.toString()
                )
              "
              ><CopyDocument
            /></el-icon>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <Clock />
                </el-icon>
                时间
              </div>
            </template>
            {{
              format(
                useFeedbackInfoStoreHook().aqiFeedback.fbTime,
                "yyyy-MM-dd HH:mm:ss"
              )
            }}
          </el-descriptions-item>

          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <office-building />
                </el-icon>
                地址
              </div>
            </template>
            {{ useFeedbackInfoStoreHook().aqiFeedback.fbAddress }}
          </el-descriptions-item>
        </el-descriptions>

        <el-divider content-position="left" border-style="dashed"
          ><h4 style="color: dimgrey">网格员信息</h4></el-divider
        >
        <el-descriptions class="mb-6" :column="1" size="small" border>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <PriceTag />
                </el-icon>
                ID
              </div>
            </template>
            {{ currentInspector.insId }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <user />
                </el-icon>
                姓名
              </div>
            </template>
            {{ currentInspector.insName }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <iphone />
                </el-icon>
                电话
              </div>
            </template>
            {{ currentInspector.insTel }}
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <tickets />
                </el-icon>
                状态
              </div>
            </template>
            <el-tag
              v-show="currentInspector.insState === 1"
              size="default"
              type="success"
              effect="dark"
              >可指派</el-tag
            >
            <el-tag
              v-show="
                currentInspector.insState === 0 ||
                currentInspector.insState === 2
              "
              size="default"
              type="danger"
              effect="dark"
              >不可指派</el-tag
            >
          </el-descriptions-item>

          <el-descriptions-item min-width="70px">
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <office-building />
                </el-icon>
                住址
              </div>
            </template>
            {{ currentInspector.insAddress }}
          </el-descriptions-item>
        </el-descriptions>

        <el-button
          round
          style="width: 95%"
          class="ml-3"
          type="warning"
          plain
          :icon="Search"
          @click="getNearestInspector()"
          >获取最近网格员</el-button
        >
        <el-button
          round
          style="width: 95%"
          class="mt-3"
          type="success"
          :disabled="currentInspector.insState !== 1"
          @click="handleShowDialog()"
          >确认指派</el-button
        >
        <el-dialog
          v-model="showDialog"
          title="请确认指派信息"
          width="800"
          align-center
        >
          <el-divider content-position="left" border-style="dashed"
            ><h4 style="color: dimgrey">反馈信息</h4></el-divider
          >
          <el-descriptions :column="1" size="small" border>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <user />
                  </el-icon>
                  ID
                </div>
              </template>
              0001<el-icon
                class="copy-btn"
                style="color: dodgerblue; margin-left: 8px"
                onmouseout="this.style.color='dodgerblue'"
                onmouseover="this.style.color='gray'"
                @click="copyPhone('0001')"
                ><CopyDocument
              /></el-icon>
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <Clock />
                  </el-icon>
                  时间
                </div>
              </template>
              {{
                format(
                  useFeedbackInfoStoreHook().aqiFeedback.fbTime,
                  "yyyy-MM-dd HH:mm:ss"
                )
              }}
            </el-descriptions-item>

            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <office-building />
                  </el-icon>
                  地址
                </div>
              </template>
              辽宁省 沈阳市 浑南区 创新路195号东北大学浑南校区
            </el-descriptions-item>
          </el-descriptions>

          <el-divider content-position="left" border-style="dashed"
            ><h4 style="color: dimgrey">网格员信息</h4></el-divider
          >
          <el-descriptions :column="1" size="small" border>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <PriceTag />
                  </el-icon>
                  ID
                </div>
              </template>
              {{ currentInspector.insId }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <user />
                  </el-icon>
                  姓名
                </div>
              </template>
              {{ currentInspector.insName }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <iphone />
                  </el-icon>
                  电话
                </div>
              </template>
              {{ currentInspector.insTel }}
            </el-descriptions-item>
            <el-descriptions-item>
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <tickets />
                  </el-icon>
                  状态
                </div>
              </template>
              <el-tag
                v-show="currentInspector.insState === 1"
                size="default"
                type="success"
                effect="dark"
                >可指派</el-tag
              >
              <el-tag
                v-show="
                  currentInspector.insState === 0 ||
                  currentInspector.insState === 2
                "
                size="default"
                type="danger"
                effect="dark"
                >不可指派</el-tag
              >
            </el-descriptions-item>

            <el-descriptions-item min-width="70px">
              <template #label>
                <div class="cell-item">
                  <el-icon :style="iconStyle">
                    <office-building />
                  </el-icon>
                  住址
                </div>
              </template>
              {{ currentInspector.insAddress }}
            </el-descriptions-item>
          </el-descriptions>
          <template #footer>
            <el-row>
              <el-col :span="4">
                <el-checkbox value="sentMessage" name="type">
                  短信通知网格员
                </el-checkbox>
              </el-col>
              <el-col :span="20">
                <div class="dialog-footer">
                  <el-button @click="showDialog = false">取消</el-button>
                  <el-button
                    effect="dark"
                    type="success"
                    @click="handleAssign()"
                  >
                    确认指派
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </template>
        </el-dialog>
      </el-col>
    </el-row>
    <el-row class="mt-4">
      <el-col :span="4">
        <el-button type="primary" size="default" @click="returnToTarget"
          >回到反馈地点</el-button
        >
      </el-col>
      <el-col :span="20">
        <el-alert
          title="在网格员表格中通过复选框选择需要在地图上显示的网格员"
          type="info"
          :closable="false"
          show-icon
          style="width: 95%"
        />
      </el-col>
      <el-col />
    </el-row>
    <el-divider content-position="left" border-style="dashed"
      ><h4 style="color: dimgrey">网格员列表</h4></el-divider
    >
    <PlusSearch
      v-model="state"
      class="mt-2, mb-4"
      :columns="searchColumns"
      :show-number="2"
      label-width="80"
      label-position="right"
      @change="handleChange"
      @search="handleSearch"
      @reset="handleRest"
    />
    <pure-table
      v-if="isShow"
      ref="tableRef"
      adaptive
      stripe
      :adaptiveConfig="adaptiveConfig"
      :data="tableData"
      :columns="columns"
      @selection-change="handleSelectionChange"
    />
    <el-pagination
      small
      background
      right
      layout="prev, pager, next"
      :page-count="totalPage"
      :page-size="pageSize"
      class="mt-4"
      @current-change="handlePageChange"
    />
  </el-card>
</template>

<script setup lang="ts">
import { ref, computed, nextTick, onMounted } from "vue";
import {
  Iphone,
  Location,
  OfficeBuilding,
  Tickets,
  User,
  PriceTag,
  CopyDocument,
  Clock,
  Odometer,
  FullScreen,
  Search
} from "@element-plus/icons-vue";
import { useMap } from "vue-baidu-map-3x";
import { useGeocoder, usePoint } from "vue-baidu-map-3x";
import { useFeedbackInfoStoreHook } from "@/store/modules/feedbackInfo";
import {
  type PlusColumn,
  PlusSearch,
  type FieldValues,
  PlusDialogForm
} from "plus-pro-components";
import { getInspectorList, getInspectorListTotalPage } from "@/api/inspector";
import "plus-pro-components/es/components/search/style/css";
import TagChromeVue from "@/layout/components/lay-tag/components/TagChrome.vue";
import { useColumns } from "./columns";
import { inspectorType } from "@/store/types";
import { all } from "axios";
import { inspect } from "util";
import { is, isNullOrUnDef } from "@pureadmin/utils";
import { now } from "@vueuse/core";
import { func } from "vue-types";
import { message } from "@/utils/message";
import router from "@/router";
import ClipboardJS from "clipboard";
import { format } from "date-fns";
import { assign } from "@/api/feedback";
import { use } from "echarts/types/src/extension.js";
import { getAqiMeasuredTaskListByInsId } from "@/api/aqiMeasuredResult";
import { listProvinces, getGridCityByProvinceId } from "@/api/province";

defineOptions({
  name: "Assign"
});

const isShow = ref(false);
const iconStyle = computed(() => {
  const marginMap = {
    large: "8px",
    default: "6px",
    small: "4px"
  };
  return {
    marginRight: marginMap["default"] || marginMap.default
  };
});

const target = ref<{ lng: number; lat: number }>();
const center = ref<string | { lng: number; lat: number }>();
const zoom = ref(16);
const showTargetInfo = ref(true);
const value1 = ref(false);
const tableData = ref<inspectorType[]>([]);
const totalPage = ref(1);
const pageSize = ref(10);
const pageNum = ref(1);
const tableRef = ref();
const multipleSelection = ref([]);
const { columns } = useColumns();
const currentInspector = ref<inspectorType>({
  insId: "",
  insTel: "",
  insPassword: "",
  insName: "",
  insState: "",
  provinceId: "",
  cityId: "",
  insAddress: "",
  remarks: ""
});
const showMarkers = ref<Marker[]>([]);
const markers = ref<Marker[]>([]);
const lastMarker = ref<Marker>(null);
const chooseSign = ref(false);
const nowMarker = ref<Marker>(null);
const showDialog = ref(false);
const disAssignBtn = ref(false);

type Marker = {
  insId: number;
  position: { lng: number; lat: number };
  icon: {
    url: string;
    size: { width: number; height: number };
  };
  inspector: inspectorType;
};

function handleShowDialog() {
  console.log(currentInspector.value, "currentInspector");
  if (currentInspector.value.insName === "") {
    message("请先选择网格员!", { type: "warning" });
  } else {
    showDialog.value = true;
  }
}
function handleAssign() {
  try {
    assign({
      fbId: useFeedbackInfoStoreHook().aqiFeedback.fbId,
      insId: currentInspector.value.insId
    }).then(res => {
      if (res.code === 200) {
        showDialog.value = false;
        router.push("/assign/success");
      } else {
        message("指派失败，请稍后再试!", { type: "error" });
      }
    });
  } catch (e) {
    console.log(e);
  }
}

//鼠标点击标记点
const handleMarkerClick = (item: any) => {
  currentInspector.value = item.inspector;
  nowMarker.value = item;

  if (lastMarker.value === null) {
    chooseSign.value = true;
    lastMarker.value = item;
    showMarkers.value[showMarkers.value.indexOf(item)].icon.size = {
      width: 70,
      height: 70
    };
    showMarkers.value[showMarkers.value.indexOf(item)].icon.url =
      "/src/assets/mapIcon/chosen.png";
    if (item.inspector.insState !== 1) {
      disAssignBtn.value = true;
    }
  } else {
    if (item !== lastMarker.value) {
      //换新标记点
      chooseSign.value = true;
      showMarkers.value[showMarkers.value.indexOf(lastMarker.value)].icon.size =
        {
          width: 60,
          height: 60
        };
      if (lastMarker.value.inspector.insState !== 1) {
        showMarkers.value[
          showMarkers.value.indexOf(lastMarker.value)
        ].icon.url = "/src/assets/mapIcon/unavailable.png";
      } else {
        showMarkers.value[
          showMarkers.value.indexOf(lastMarker.value)
        ].icon.url = "/src/assets/mapIcon/available.png";
      }

      console.log(lastMarker.value, "lastMarker");
      console.log(
        showMarkers.value[showMarkers.value.indexOf(lastMarker.value)],
        "show"
      );

      lastMarker.value = item;

      showMarkers.value[showMarkers.value.indexOf(item)].icon.size = {
        width: 70,
        height: 70
      };
      showMarkers.value[showMarkers.value.indexOf(item)].icon.url =
        "/src/assets/mapIcon/chosen.png";

      if (item.inspector.insState !== 1) {
        disAssignBtn.value = true;
      }
    } else {
      //取消标记点
      chooseSign.value = false;
      lastMarker.value = null;
      currentInspector.value = {
        insId: "",
        insTel: "",
        insPassword: "",
        insName: "",
        insState: "",
        provinceId: "",
        cityId: "",
        insAddress: "",
        remarks: ""
      };
      nowMarker.value = null;
    }
  }
};

//鼠标移入标记点
const handleMarkerMouseover = (item: any) => {
  currentInspector.value = item.inspector;
  showMarkers.value[showMarkers.value.indexOf(item)].icon.size = {
    width: 70,
    height: 70
  };
};

//鼠标移出标记点
const handleMarkerMouseout = (item: any) => {
  if (chooseSign.value && item.inspector.insId === nowMarker.value.insId) {
  } else {
    showMarkers.value[showMarkers.value.indexOf(item)].icon.size = {
      width: 60,
      height: 60
    };
    showMarkers.value[showMarkers.value.indexOf(item)].icon.url =
      "/src/assets/mapIcon/chosen.png";
    if (item.inspector.insState !== 1) {
      showMarkers.value[showMarkers.value.indexOf(item)].icon.url =
        "/src/assets/mapIcon/unavailable.png";
    } else {
      showMarkers.value[showMarkers.value.indexOf(item)].icon.url =
        "/src/assets/mapIcon/available.png";
    }
    currentInspector.value = nowMarker.value.inspector;
  }
};

//自定义选中项
const toggleSelection = (rows?: any) => {
  const { toggleRowSelection, clearSelection } = tableRef.value.getTableRef();
  if (rows) {
    rows.forEach(row => {
      toggleRowSelection(row, undefined);
    });
  } else {
    clearSelection();
  }
};
//获取多选选中项
const handleSelectionChange = val => {
  multipleSelection.value = val;
  showMarkers.value = [];
  val.forEach(item => {
    markers.value.forEach(marker => {
      if (marker.insId === item.insId) {
        showMarkers.value.push(marker);
      }
    });
  });
};

onMounted(() => {
  getTableTotalPage();
  getTableData();

  target.value = useFeedbackInfoStoreHook().aqiFeedback.fbAddress;
  setTimeout(() => {
    isShow.value = true;
  }, 800);

  getProvinceList();
});

const getProvinceList = async () => {
  try {
    const { data } = await listProvinces();
    console.log("provinces");
    console.log(data);
    const provinces = data.map(province => ({
      value: province.provinceId,
      label: province.provinceName,
      children: []
    }));
    for (const province of provinces) {
      const cityData = (await getGridCityByProvinceId(province.value)).data;
      const cities = cityData.map(city => ({
        value: city.cityId,
        label: city.cityName
      }));
      // 将城市信息添加到对应省份的children属性中
      province.children = cities;
      console.log(province, "children");
    }
    return provinces;
  } catch (e) {
    console.log(e);
  }
};

function copyPhone(data: string) {
  let clipboard = new ClipboardJS(".copy-btn", {
    text: () => {
      //返回需要复制的字符串
      return data;
    }
  });
  clipboard.on("success", () => {
    clipboard.destroy();
  });
  clipboard.on("error", () => {
    clipboard.destroy();
  });

  message("已复制", { type: "success" });
}

//初始化地图描点数据
const initMarkers = (list: []) => {
  Array.from(list).forEach(item => {
    const aMarker: Marker = {
      insId: item.insId,
      position: { lng: 0, lat: 0 },
      icon: {
        url: "/src/assets/mapIcon/available.png",
        size: { width: 60, height: 60 }
      },
      inspector: item
    };

    useGeocoder().then(geocoder => {
      geocoder.getPoint(item.insAddress, res => {
        aMarker.position = res;
        if (item.insState !== 1) {
          aMarker.icon.url = "/src/assets/mapIcon/unavailable.png";
        }
        markers.value.push(aMarker);
        showMarkers.value.push(aMarker);
        console.log(showMarkers.value, "marker");
      });
    });
  });
};

const inspectorParam = ref({});

//初始化表格数据
const getTableData = async () => {
  try {
    const { data } = await getInspectorList({
      inspectorParam: inspectorParam.value,
      pageSize: pageSize.value,
      pageNum: pageNum.value
    });
    const promises = data.list.map(async item => {
      const unfinishedTaskNum = await getUnfinishedTaskNum(item.insId);
      item.remarks = unfinishedTaskNum.toString();
    });
    await Promise.all(promises);
    tableData.value = data.list;
    initMarkers(tableData);
    console.log(data.list);
  } catch (e) {
    console.log(e);
  }
  initMarkers(tableData);
};
const getTableTotalPage = async () => {
  try {
    const total = await getInspectorListTotalPage({
      inspectorParam: {},
      pageSize: 10
    });
    totalPage.value = total.data;
  } catch (e) {
    console.log(e);
  }
};

//获取网格员未完成任务数
const getUnfinishedTaskNum = async (insId: number) => {
  console.log(insId, "insId");
  const { data } = await getAqiMeasuredTaskListByInsId(insId);
  if (data === null || data === undefined) {
    return 0;
  }
  let unfinishedTaskNum = 0;

  console.log(data, "data");
  data.forEach(task => {
    if (task.aqiMeasuredResult.aqimrState === 0) {
      unfinishedTaskNum++;
    }
  });
  console.log(unfinishedTaskNum, "Unfinished Task Num");
  return unfinishedTaskNum;
};

//获取最近网格员
function getDistance(marker1: Marker, marker2: { lng: number; lat: number }) {
  let lng = marker1.position.lng - marker2.lng;
  let lat = marker1.position.lat - marker2.lat;
  let distance = Math.sqrt(lng * lng + lat * lat) * 1000;
  return distance;
}
const getNearestInspector = () => {
  if (showMarkers.value.length === 0) {
    message("暂无网格员", { type: "warning" });
  }
  let minDistance = getDistance(showMarkers.value[0], target.value);
  let marker = showMarkers.value[0];
  for (let i = 1; i < showMarkers.value.length; i++) {
    if (getDistance(showMarkers.value[i], target.value) < minDistance) {
      minDistance = getDistance(showMarkers.value[i], target.value);
      marker = showMarkers.value[i];
    }
  }
  message(`最近网格员：${marker.inspector.insName}`, { type: "info" });
  currentInspector.value = marker.inspector;
  center.value = marker.position;
};

//分页
const handlePageChange = (currentPage: number) => {
  pageNum.value = currentPage;
  getTableData();
};
//表格大小自适应
const adaptiveConfig: AdaptiveConfig = {
  /** 表格距离页面底部的偏移量，默认值为 `96` */
  offsetBottom: 85,
  /** 是否固定表头，默认值为 `true`（如果不想固定表头，fixHeader设置为false并且表格要设置table-layout="auto"） */
  fixHeader: true
};
//双向绑定中心点和缩放级别
const syncCenterAndZoom = e => {
  const { lng, lat } = e.target.getCenter();
  zoom.value = e.target.getZoom();
  center.value = { lng, lat };
  nextTick(() => {
    center.value.lng = lng;
    center.value.lat = lat;
  });
};
// 回到反馈地点
const returnToTarget = () => {
  // useGeocoder().then(geocoder => {
  //   geocoder.getPoint(useFeedbackInfoStoreHook().aqiFeedback.fbAddress, res => {
  //     center.value = res;
  //   });
  // });
  center.value = target.value;
  zoom.value = 16;
};
//初始化中心点和缩放级别
const handleMapReady = ({ BMap, map }) => {
  zoom.value = 16;
  useGeocoder().then(geocoder => {
    geocoder.getPoint(useFeedbackInfoStoreHook().aqiFeedback.fbAddress, res => {
      target.value = res;
      center.value = res;
    });
  });
  initMarkers(tableData.value);
};

//搜索表单配置
const searchColumns: PlusColumn[] = [
  {
    label: "名称",
    prop: "insName",
    valueType: "copy",
    tooltip: "名称最多显示6个字符"
  },
  {
    label: "状态",
    prop: "insState",
    valueType: "select",
    options: [
      {
        label: "不可指派",
        value: 0,
        color: "red"
      },
      {
        label: "可指派",
        value: 1,
        color: "blue"
      }
    ]
  },
  {
    label: "电话",
    prop: "insTel",
    valueType: "copy",
    tooltip: "电话应为11位有效数字"
  },
  {
    label: "城市",
    prop: "province",
    valueType: "cascader",
    options: getProvinceList()
  },
  {
    label: "地区",
    prop: "insAddress",
    tooltip: "请精确到门牌号",
    fieldProps: {
      placeholder: "请精确到门牌号"
    }
  }
];

//搜索表单事件
const state = ref({
  status: "0",
  time: new Date().toString()
});
const handleChange = (values: any) => {
  console.log(values, "change");
};
const handleSearch = (values: any) => {
  let provinceId = values.province?.[0] ?? null;
  let cityId = values.province?.[1] ?? null;
  let insId = values.insId ?? null;
  let insState = values.insState ?? null;
  let insAddress = values.insAddress ?? null;
  let insName = values.insName ?? null;
  inspectorParam.value = {
    provinceId,
    cityId,
    insId,
    insState,
    insAddress,
    insName,
    ...values
  };
  getTableData();
  getTableTotalPage();
  console.log(values, "search");
};
const handleRest = () => {
  inspectorParam.value = {};
  getTableData();
  getTableTotalPage();
  console.log("handleRest");
};
</script>

<style scoped>
.bm-view {
  width: 100;
  height: 490px;
}
</style>
